using System;
using System.Collections.Generic;
using Framework.Utils.SingletonTemplate;

namespace ToffeeHttp.Runtime.Core
{
    public class ToffeeHttpClient
    {

        private Dictionary<string, HttpConfig> _httpConfigs = new Dictionary<string, HttpConfig>();

        private const string _DEFAULT_SERVER = "DEFAULT_SERVER";

        public void SetServerConfig(Dictionary<string, HttpConfig> configs)
        {
            if (configs != null)
            {
                this._httpConfigs = configs;
            }
        }

        public void AppendServer<T, T1>(string serverPath, int port, int timeOut, string serverGroup = _DEFAULT_SERVER) where T : IRequestHandler, new() where T1 : IMsgChannel, new()
        {
            var handler = new T();
            var channel = new T1();
            this.AppendServer(handler, channel, serverPath, port, timeOut, serverGroup);
        }

        public void AppendServer(IRequestHandler requestHandler, IMsgChannel channel, string serverPath, int port, int timeOut, string serverGroup = _DEFAULT_SERVER)
        {
            this._httpConfigs[serverGroup] = new HttpConfig()
                                             {
                                                 ServerPath     = serverPath,
                                                 Port           = port,
                                                 TimeOut        = timeOut,
                                                 RequestHandler = requestHandler,
                                                 MsgChannel     = channel
                                             };
        }

        public void SendHttp(string method, object data, Action<HttpResponse> callback, string serverGroup = _DEFAULT_SERVER)
        {
            if (this._httpConfigs.ContainsKey(serverGroup) == false)
            {
                throw new Exception("无效ServerGroup，请检查是否配置了指定服务器接口");
            }

            var server  = this._httpConfigs[serverGroup];
            var request = this.CreateRequest(method, data, server);
            request.Send(callback);
        }

        public void SendHttp(string method, object data, Action<HttpResponse> callback, HttpConfig server)
        {
            var request = this.CreateRequest(method, data, server);
            request.Send(callback);
        }

        public HttpRequest CreateRequest(string method, object data, HttpConfig server)
        {
            Uri uri         = new Uri(server.ServerPath + ":" + server.Port + method);
            var httpRequest = new HttpRequest(server.RequestHandler, server.MsgChannel, uri, data);
            httpRequest.webRequest.timeout = server.TimeOut;
            return httpRequest;
        }

    }
}